package cn.zl.ZLM.service.impl;

import cn.zl.GB28181.core.SSRCInfo;
import cn.zl.GB28181.session.SSRCFactory;
import cn.zl.ZLM.ZLMLayer;
import cn.zl.ZLM.core.ZLMApi;
import cn.zl.ZLM.event.callback.inter.IMKRtpServerDetachCallBack;
import cn.zl.ZLM.helper.ZLMApiHelper;
import cn.zl.ZLM.service.IZLMService;
import cn.zl.ZLM.structure.MK_RTP_SERVER;
import cn.yunbamboos.Const;
import cn.zl.common.ZLConst;
import cn.zl.config.ZLConfig;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ZLMServiceImpl implements IZLMService {

    private static final Logger logger = LoggerFactory.getLogger(ZLMServiceImpl.class);

    @Resource
    private ZLMLayer layer;
    @Resource
    private ZLConfig config;
    @Resource
    private SSRCFactory ssrcFactory;

    @Override
    public SSRCInfo openRTPServer(String streamId, int tcpMode, boolean ssrcCheck) {
        // 获取mediaServer可用的ssrc
        String ssrc = ssrcFactory.getPlaySsrc();
        if (streamId == null) {
            streamId = String.format("%08x", Long.parseLong(ssrc)).toUpperCase();
        }
        if (ssrcCheck && tcpMode > 0) {
            // 目前zlm不支持 tcp模式更新ssrc，暂时关闭ssrc校验
            logger.warn("[openRTPServer] 平台对接时下级可能自定义ssrc，但是tcp模式zlm收流目前无法更新ssrc，可能收流超时，此时请使用udp收流或者关闭ssrc校验");
        }
        ZLMApi ZLM_API = ZLMApiHelper.getInstance().getApi();
        //模式(tcp_mode 0:Udp 1:TCP)
        MK_RTP_SERVER mkRtpServer = ZLM_API.mk_rtp_server_create2((short) 30000, tcpMode, ZLConst.GB28181.VHOST, ZLConst.GB28181.APP, streamId);
        //服务器接收流超时时触发
        IMKRtpServerDetachCallBack imkRtpServerDetachCallBack = user_data -> {
            //收流超时释放端口 超时时间设置在rtp_proxy.timeoutSec
            ZLM_API.mk_rtp_server_release(new MK_RTP_SERVER(user_data));
        };
        ZLM_API.mk_rtp_server_set_on_detach(mkRtpServer, imkRtpServerDetachCallBack, mkRtpServer.getPointer());

        return new SSRCInfo(30000, ssrc, streamId);
    }

    public void closeRTPServer(String streamId, int tcpMode, boolean ssrcCheck) {
        ZLMApi ZLM_API = ZLMApiHelper.getInstance().getApi();
        ZLM_API.mk_rtp_server_release(null);
    }

}
